package com.example.controller;

import com.example.common.api.ApiResult;
import com.example.service.AsyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/async")
public class AsyncController {
    
    private static final Logger log = LoggerFactory.getLogger(AsyncController.class);
    
    private final AsyncService asyncService;
    
    public AsyncController(AsyncService asyncService) {
        this.asyncService = asyncService;
    }
    
    /**
     * 测试异步任务
     */
    @PostMapping ("/test/{name}")
    public ApiResult<String> testAsync(@PathVariable("name") String taskName) {
        log.info("收到异步任务请求: {}", taskName);
        
        // 启动异步任务
        CompletableFuture<String> future = asyncService.executeAsyncTask(taskName);
        
        // 非阻塞方式处理结果
        future.thenAccept(result -> {
            log.info("异步任务完成: {}", result);
        });
        
        return ApiResult.success("异步任务已启动: " + taskName);
    }
    
    /**
     * 获取异步任务结果（阻塞方式）
     */
    @GetMapping("/result/{name}")
    public ApiResult<String> getAsyncResult(@PathVariable("name") String taskName) {
        try {
            // 启动异步任务并等待结果
            CompletableFuture<String> future = asyncService.executeAsyncTask(taskName);
            String result = future.get(); // 阻塞直到任务完成
            
            return ApiResult.success(result);
        } catch (InterruptedException | ExecutionException e) {
            Thread.currentThread().interrupt();
            log.error("获取异步结果失败: {}", e.getMessage());
            return ApiResult.failed("获取异步结果失败: " + e.getMessage());
        }
    }
    
    /**
     * 并行执行多个异步任务
     */
    @GetMapping("/parallel/{name}")
    public ApiResult<Map<String, String>> executeParallelTasks(@PathVariable("name") String baseName) {
        // 启动两个不同的异步任务
        CompletableFuture<String> task1 = asyncService.executeAsyncTask(baseName + "-1");
        CompletableFuture<String> task2 = asyncService.executeIoTask(baseName + "-2");
        
        // 等待所有任务完成
        CompletableFuture<Void> allTasks = CompletableFuture.allOf(task1, task2);
        
        try {
            allTasks.get(); // 等待所有任务完成
            
            // 收集结果
            Map<String, String> results = new HashMap<>();
            results.put("task1", task1.get());
            results.put("task2", task2.get());
            
            return ApiResult.success(results);
        } catch (InterruptedException | ExecutionException e) {
            Thread.currentThread().interrupt();
            log.error("执行并行任务失败: {}", e.getMessage());
            return ApiResult.failed("执行并行任务失败: " + e.getMessage());
        }
    }
}